<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习7</title>
</head>

<body>

</body>
<script>
    //1.求10-20之间的随机数
    function getRandom() {
        return Math.floor(Math.random() * 11) + 10;
    }
    console.log(getRandom())

    //2.随机生成颜色 例如：#3c3c3c
    function getRandomColor() {
        let str = '0123456789abcdef';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += str.charAt(Math.floor(Math.random() * 16));
        }
        return color;
    }
    console.log(getRandomColor());

    //1.写一个函数，格式化日期对象，返回yyyy-MM-dd HH:mm:ss的形式
    function formatDate(date) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();

        function addZero(num) {
            return num < 10 ? '0' + num : num;
        }

        return year + '-' + addZero(month) + '-' + addZero(day) + ' ' +
            addZero(hour) + ':' + addZero(minute) + ':' + addZero(second);
    }

    console.log(formatDate(new Date()));

    //2.计算时间差，返回相差的天/时/分/秒
    function getTimeDiff(startDate, endDate) {
        let diff = Math.abs(endDate - startDate);

        let days = Math.floor(diff / (1000 * 60 * 60 * 24));
        diff -= days * (1000 * 60 * 60 * 24);

        let hours = Math.floor(diff / (1000 * 60 * 60));
        diff -= hours * (1000 * 60 * 60);

        let minutes = Math.floor(diff / (1000 * 60));
        diff -= minutes * (1000 * 60);

        let seconds = Math.floor(diff / 1000);

        return days + "/" + hours + "/" + minutes + "/" + seconds

    }

    let start = new Date('2024-05-10 10:00:00');
    let end = new Date('2024-05-15 14:30:45');
    console.log(getTimeDiff(start, end));
</script>

</html>